/**
 * Created by shitao on 15/10/17.
 */

(function () {
    // 创建service对象
    angular.module('my-tabs.services')
        .factory('friendService', friendService);
    // 申明依赖
    friendService.$inject = ['friendApi', 'sessionService'];

    function friendService(friendApi, session) {

        var mines = [],
            dialogs = {};

        return {

            load: function () {
                return friendApi.getFriends()
                    .success(function (items) {
                        mines.length = 0;
                        _.each(items, function (item) {
                            mines.push(item);
                        })
                    });
            },

            all: function () {
                return mines;
            },

            get: function (friendId) {
                for (var i = 0; i < mines.length; i++) {
                    if (mines[i].id === parseInt(friendId)) {
                        return mines[i];
                    }
                }
                return null;
            },

            dialog: function (friendId) {
                var friend = this.get(friendId),
                    dialog = [];
                if (friend) {
                    if (!dialogs.hasOwnProperty(friendId)) {
                        dialogs[friendId] = dialog;
                        friendApi.getDialog(friend, session.getSignInUser())
                            .then(function (items) {
                                _.each(items, function (item) {
                                    dialog.push(item);
                                });
                            })
                    } else {
                        dialog = dialogs[friendId];
                    }
                }
                return dialog;
            }

        };
    };
})();
